//
//  FPSLabel.swift
//  FloatClock
//
//  Created by runbey_dev_ios on 2023/6/21.
//

import Foundation
import UIKit
 
class FPSLabel: UILabel {
 
    private var link:CADisplayLink?
    private var lastTime:TimeInterval = 0.0;
    private var count:Int = 0;
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        link = CADisplayLink.init(target: self, selector: #selector(FPSLabel.didTick(link:)))
        //commom会无论app处于什么停止还是滑动都会进行fps打印(commonMode会添加timer到所有mode上面)
        link?.add(to: RunLoop.current, forMode: .common)
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }
    
    @objc func didTick(link:CADisplayLink) {
        if lastTime == 0{
            lastTime = link.timestamp
            return
        }
        //用来记录一秒进入这个方法多少次
        count += 1
        //在一秒内打印的次数
        let delta = link.timestamp - lastTime
        if delta < 1{
            //不够一秒就返回，继续往上面count加一，这样就可以获得一秒内有多少个页面
            return
        }
        //到一秒了就把lastTime更新至当前时间记录下俩下一次计算
        lastTime = link.timestamp
        let fps = Double(count)/delta
        count = 0
        text = String.init(format: "%02.0fHZ", round(fps))
        print(text ?? "0")
    }
 
}

